// 商品列表
import './css/GoodList.less'
import '../../css/public.less'
import zh_CN from 'antd/es/locale/zh_CN';
import React, { useState, useEffect } from 'react'
import { Input, message, Select, Table, Switch, Modal, Upload, Form, Checkbox, Divider, ConfigProvider } from 'antd';

import { UpOutlined, PlusOutlined } from '@ant-design/icons';
import Modify from '../goods/child/GoodList/Modify'
import Check from '../goods/child/GoodList/Check'
import type { ColumnsType } from 'antd/es/table';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import { getStateNum, getShopList, getClassificationOne, getClassificationTwo, getSearchGood, getBrandName, baseUrl, getBatch, getSort } from '../../../api/lf'
import { constants } from 'buffer';
const CheckboxGroup = Checkbox.Group;
/* 商品详情 */
interface DataType {
  key: React.Key;
  goodsId: string;//商品序号
  goodsImg: string;//商品图片
  goodsName: string;//商品名字
  goodsSerNum: number;//商品货号
  goodsPriceRange: string;//商品价格区间
  categoryName: string;//类别
  brandName: string;//品牌名baseUrl
  goodsBrandId: number;//品牌id
  goodsStatus: string;//是否上架
  goodsSell: string;//销量
}


/* 分类 */
interface getClassificationType {
  value: number,
  label: string
}



export default function GoodList() {

  const [allShop, setAllShop] = useState<number>()//全部商品
  const [shelfShop, setShelfShop] = useState<number>()//已上架商品
  const [noShelfShop, setNoShelfShop] = useState<number>()//未上架商品
  const [upDown, setDown] = useState<string>('all')//记录顶部按钮谁被按下
  const [data, setData] = useState<DataType[]>([]) /* 表格列数据 */
  const [inputValue, setInputValue] = useState<string>('')//按关键词搜索
  const [brandNameArr, setBrandNameArr] = useState<getClassificationType[]>()//品牌名
  const [goodsBrandId, setGoodsBrandId] = useState<string>()//品牌id
  const [searchIsShow, setSearchIsShow] = useState<Boolean>(true)//控制搜索栏是否隐藏
  const [brandArr, setBrandArr] = useState<getClassificationType[]>([])//搜索下拉框 一级分类
  const [brandArr2, setBrandArr2] = useState<getClassificationType[]>([])//搜索下拉框 二级分类
  const [goodsCategoryId, setGoodsCategoryId] = useState<string>()//商品类型ID
  const [goodsStatus, setGoodsStatus] = useState<string>()//上下架ID
  const [shelfArr, setShelfArr] = useState([
    { value: '4', label: '上架' },
    { value: '5', label: '下架' },

  ])//按是否上架搜索下拉框

  //排序方式下拉框
  const [sort, setSort] = useState([
    { value: 1, label: '按价格顺序' },
    { value: 2, label: '按价格倒序' },
    { value: 3, label: '按销量顺序' },
    { value: 4, label: '按销量倒序' },
    { value: 5, label: '按上架时间顺序' },
    { value: 6, label: '按上架时间倒序' },
  ])

  //关联标签
  const plainOptions = ['标签1', '标签2', '标签3', '标签4', '标签5', '标签6'];
  const defaultCheckedList = ['1', '2', '3', '4', '5', '6'];

  const [batch, setBatch] = useState([
    { label: '批量上架', value: 4 },
    { label: '批量下架', value: 5 },

  ])//批量操作下拉框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);//编辑商品弹框
  const [isModalOpen2, setIsModalOpen2] = useState(false);//查看商品弹框
  const [isModalOpen3, setIsModalOpen3] = useState(false);//获取商品链接弹框
  const [isModalOpen4, setIsModalOpen4] = useState(false);//删除商品链接弹框

  const [indeterminate, setIndeterminate] = useState(true);//关联标签是否全选
  const [checkAll, setCheckAll] = useState(false)//关联标签是否全选
  const [checkedList, setCheckedList] = useState<CheckboxValueType[]>(defaultCheckedList);//已选的标签

  const [modInfo, setModInfo] = useState<DataType | null>(null)//传给修改组件的数据

  const [cheInfo, setCheInfo] = useState<DataType | null>(null)//传给查看组件的数据
  const [delId, setDelId] = useState<number[]>([])//要删除商品的ID
  const [sortId, setSortId] = useState<number[]>([])//存多选框拿到的id
  /* 表格列名 */
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'goodsId',
      width: '6%',
      align: 'center',
    },
    {
      title: '商品图片',
      dataIndex: 'goodsImg',
      align: 'center',
      render: (value, record) => {
        return (
          <div><img src={baseUrl + value} /></div>
        )
      }



    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      align: 'center',
    },
    {
      title: '货号',
      dataIndex: 'goodsSerNum',
      align: 'center',
    },
    {
      title: '价格',
      dataIndex: 'goodsPriceRange',
      align: 'center',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
      align: 'center',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      align: 'center',
    },
    {
      title: '是否上架',
      dataIndex: 'goodsStatus',
      align: 'center',
      render: (_, record) => <Switch checked={record.goodsStatus == '4' ? true : false} onClick={statusClick} />
    },
    {
      title: '销量',
      dataIndex: 'goodsSell',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '18%',
      align: 'center',
      render: (_, record) => <div >
        <button className='edit' onClick={() => edit(record)}>编辑商品</button>
        <button className='show' onClick={() => check(record)}>查看</button>
        <button className='link' onClick={() => link(record)}>生成链接</button>
        <button className='del' onClick={() => del(record)}>删除</button>
      </div>
    },
  ];

  /* 给表格数据添加Key */
  function pushListKey(arr: any) {
    const data: DataType[] = [];
    for (let i = 0; i < arr.length; i++) {
      data.push({
        key: i,
        goodsId: arr[i].goodsId,//商品序号
        goodsImg: arr[i].goodsImg,//商品图片
        goodsName: arr[i].goodsName,//商品名字
        goodsSerNum: arr[i].goodsSernum,//商品货号
        goodsPriceRange: arr[i].goodsPriceRange,//商品价格区间
        categoryName: arr[i].categoryName,//类别
        brandName: arr[i].brandName,//品牌名
        goodsBrandId: arr[i].goodsBrandId,//品牌ID
        goodsStatus: arr[i].goodsStatus,//是否上架
        goodsSell: arr[i].goodsSell,//销量

      });
    }

    setData(data)

  }

  useEffect(() => {
    upBtn('all'),
      getAllShop(),
      getAllStateNum(),
      getUpStateNum(),
      getDownStateNum(),
      getClassification(),
      getAllBrandName()
  }, [])

  //获取所有商品
  function getAllShop() {
    getShopList(
      { limit: 10, page: 1 }
    ).then(res => {
      console.log('全部商品', res);
      pushListKey(res.data.data)
    }).catch(err => {
      console.log('请求失败', err
      );

    })
  }
  //获取商品状态数量
  function getAllStateNum() {
    getStateNum().then(res => {
      /*  console.log('全部商品', res); */
      setAllShop(res.data)
    }).catch(err => {
      console.log('请求失败', err);

    })
  }
  //获取已上架商品状态数量
  function getUpStateNum() {
    getStateNum({ status: 4 }).then(res => {
      /* console.log('已上架商品', res); */
      setShelfShop(res.data)
    }).catch(err => {
      console.log('请求失败', err);
    })
  } //获取未上架商品状态数量
  function getDownStateNum() {
    getStateNum({ status: 5 }).then(res => {
      /* console.log('未上架商品', res); */
      setNoShelfShop(res.data)
    }).catch(err => {
      console.log('请求失败', err);
    })
  }


  const upBtn = (v: string) => {
    setDown(v)
    /* console.log(upDown); */

  }
  //获取分类查询的第一类
  function getClassification() {
    getClassificationOne().then(res => {
      /* console.log('第一类', res); */
      let oneData: getClassificationType[] = [];
      for (let i = 0; i < res.data.length; i++) {
        oneData.push(
          {
            value: res.data[i].categoryId,
            label: res.data[i].categoryName
          }
        )
      }
      /* console.log('oneData', oneData); */
      setBrandArr(oneData)
    }).catch(err => {
      console.log('请求失败', err);

    })
  }

  //获取所有品牌
  function getAllBrandName() {
    getBrandName().then(res => {
      /* console.log('所有品牌', res.data); */
      let arr = res.data.map((item) => {
        return Object.assign({}, { value: item.brandId, label: item.brandName })
      })
      /* console.log(arr) */
      setBrandNameArr(arr)


    }).catch(err => {
      console.log('请求失败', err);

    })
  }

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);

      let arr = selectedRows.map(item => {
        return Number(item.goodsId)
      })
      setSortId(arr)
      console.log('arr', arr);


    },

  };

  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');

  //获取按关键词搜索内容
  const inputChange = (e: any) => {
    console.log('按关键词搜索内容', e.target.value);
    setInputValue(e.target.value)

  }

  //获取按品牌搜索内容
  const handleChange = (value: string) => {
    console.log(`按品牌搜索 ${value}`);
    setGoodsBrandId(value)

  };
  //批量操作
  const handleChange2 = (value: string) => {
    console.log(`批量操作 ${value}`);
    setGoodsStatus(value)
    console.log('发请求');
    getBatch({ ids: sortId, status: value }).then(res => {
      console.log('批量上架', res
      );

      getAllShop()
      message.success('已修改', 2)
    }).catch(err => {
      console.log('err', err);
      message.error('请选择商品', 2)
    })

  };

  //排序方式
  const handleChange3 = (value: string) => {
    console.log(`排序方式 ${value}`);
    if (value == '1') {
      console.log('发请求');
      getSort({ limit: 10, page: 1, name: 'goods_price_range', orderNum: '2' }).then(res => {
        console.log('成功', res);
        message.success('已修改', 2)
        pushListKey(res.data.data)
      }).catch(err => {
        console.log('失败', err);

      })
    } else if (value == '2') {
      console.log('发请求');
      getSort({ limit: 10, page: 1, name: 'goods_price_range', orderNum: '1' }).then(res => {
        console.log('成功', res);
        message.success('已修改', 2)
        pushListKey(res.data.data)
      }).catch(err => {
        console.log('失败', err);

      })
    } else if (value == '3') {
      console.log('发请求');
      getSort({ limit: 10, page: 1, name: 'goods_sell', orderNum: '2' }).then(res => {
        console.log('成功', res);
        message.success('已修改', 2)
        pushListKey(res.data.data)
      }).catch(err => {
        console.log('失败', err);

      })
    } else if (value == '4') {
      console.log('发请求');
      getSort({ limit: 10, page: 1, name: 'goods_sell', orderNum: '1' }).then(res => {
        console.log('成功', res);
        message.success('已修改', 2)
        pushListKey(res.data.data)
      }).catch(err => {
        console.log('失败', err);

      })
    } else if (value == '5') {
      console.log('发请求');
      getSort({ limit: 10, page: 1, name: 'goods_ontime', orderNum: '2' }).then(res => {
        console.log('成功', res);
        message.success('已修改', 2)
        pushListKey(res.data.data)
      }).catch(err => {
        console.log('失败', err);

      })
    } else if (value == '6') {
      console.log('发请求');
      getSort({ limit: 10, page: 1, name: 'goods_ontime', orderNum: '1' }).then(res => {
        console.log('成功', res);
        message.success('已修改', 2)
        pushListKey(res.data.data)
      }).catch(err => {
        console.log('失败', err);

      })
    }

  };

  //按商品分类搜索
  const firstChange = (value: number) => {
    console.log(`商品分类1 ${value}`);
    getClassificationTwo({ id: value }).then(res => {
      console.log('商品分类1对应的子分类', res);
      let twoData: getClassificationType[] = []
      for (let i = 0; i < res.data.length; i++) {
        twoData.push({
          value: res.data[i].categoryId,
          label: res.data[i].categoryName
        })
      }
      /*   console.log('二级分类', twoData); */
      setBrandArr2(twoData)
    }).catch(err => {
      console.log('请求失败', err);

    })

  };
  const secondChange = (value: string) => {
    console.log(`商品分类2 ${value}`);
    setGoodsCategoryId(value)
  };

  //重置按钮
  const reset = () => {
    getAllShop()
  }


  //查询按钮
  const searchBtn = () => {
    console.log('点击了查询');
    if (!inputValue && !goodsBrandId && !goodsCategoryId && !goodsCategoryId && !goodsStatus) {
      message.error('查询内容不能为空', 2)
      return
    }
    getSearchGood({ limit: 10, page: 1, goodsName: inputValue, goodsBrandId: goodsBrandId, goodsCategoryId: goodsCategoryId, goodsStatus: goodsStatus }).then(res => {
      console.log('查询出来的商品', res);
      message.success('查询成功', 2)
      pushListKey(res.data.data)
    }).catch(err => {
      console.log('请求失败', err);
      message.error('查询失败', 2)
    })
  }

  //搜索区是否隐藏
  const isShow = () => {
    let isShow = !searchIsShow
    setSearchIsShow(isShow)


  }
  //上架按钮
  const statusClick = (checked: boolean) => {
    console.log('1111', checked);
    checked = false
  };
  //查看商品按钮 发起请求获取该商品数据
  const check = (record: any) => {
    console.log(record);
    setCheInfo(record)
    setIsModalOpen2(true);
  }
  //编辑商品按钮 发起请求获取该商品数据
  const edit = (record: any) => {
    console.log(record);
    setIsModalOpen(true);
    setModInfo(record)
  }
  //生成商品链接按钮 发起请求获取该商品数据
  const link = (record: any) => {
    console.log(record);
    setIsModalOpen3(true);
  }
  //删除商品按钮 发起请求获取该商品数据
  const del = (record: any) => {
    let delArr = []
    delArr.push(record.goodsId)
    setDelId(delArr)
    setIsModalOpen4(true);
  }
  //编辑商品弹框 确认 发起请求
  const handleOk = () => {
    setIsModalOpen(false);

    setIsModalOpen2(false);

    message.success('编辑成功', 2)
  };
  //查看商品弹框 确认 
  const handleOk2 = () => {
    setIsModalOpen2(false);

  };
  //查看商品链接弹框 确认 
  const handleOk3 = () => {
    setIsModalOpen3(false);

  };
  //删除商品弹框 确认  发起请求
  const handleOk4 = () => {


    console.log('发请求');
    getBatch({ ids: delId, status: '6' }).then(res => {
      console.log('删除成功', res);
      getAllShop()
      message.success('删除成功', 2)
    }).catch(err => {
      console.log('请求失败', err);
      message.error('删除失败', 2)
    })
    setIsModalOpen4(false);

  };
  //删除商品弹框 确认  发起请求

  //编辑/查看/链接/删除商品弹框 取消
  const handleCancel = () => {
    setIsModalOpen(false);
    setIsModalOpen2(false);
    setIsModalOpen3(false);
    setIsModalOpen4(false);

  };
  const onFinish = (value: any) => {
    console.log(value);

  }

  //选择标签的方法

  const onCheckChange = (list: CheckboxValueType[]) => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < plainOptions.length);
    setCheckAll(list.length === plainOptions.length);
    console.log('选择标签', list);
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? plainOptions : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
    console.log('选择标签', checkedList);

  };
  //
  return (
    <>
      <div className='GoodList'>
        {/* 头部 */}
        <div className='page-top'>
          {/* 左边标题 */}
          <div className='page-title'>
            <p>商品列表</p>
          </div>
        </div>
        {/* 商品数量及分类 */}
        <div className='goods-num'>
          <div className={upDown == 'all' ? 'upBtn' : ''} onClick={() => upBtn('all')}>全部商品( <p>{allShop}</p> )</div>
          <div onClick={() => upBtn('shelf')}>已上架( <p>{shelfShop}</p> )</div>
          <div onClick={() => upBtn('under')}>未上架( <p>{noShelfShop} </p> )</div>
        </div>
        {/* 内容 */}
        <div className='page-context' style={{ paddingTop: '10px' }}>

          {/* 搜索 */}
          <div className='goods-search'>
            <div className='search-title'>
              <p>商品筛选</p>
              <div onClick={isShow}>{searchIsShow ? '收起' : '展开'}&nbsp;<UpOutlined style={{ transform: (searchIsShow) ? 'none' : 'rotate(180deg)' }} /></div>
            </div>
            <div className='search-content' style={{ display: (searchIsShow) ? 'block' : 'none' }}>
              <div className='search-content1'>
                <div >
                  <span>关键词</span>
                  <Input className='input1' placeholder=" 商品名称" onChange={inputChange} /></div>
                <div >
                  <span>品牌</span>
                  <Select
                    className='Select1'
                    defaultValue="全部"

                    onChange={handleChange}
                    options={brandNameArr}
                  /></div>
                <div>
                  <span>是否上架</span>
                  <Select
                    className='Select1'
                    defaultValue="全部"
                    onChange={handleChange2}
                    options={shelfArr}
                  /></div>

              </div>
              <div>
                <div style={{ paddingLeft: "15px" }} >
                  <span>分类</span>
                  <Select
                    className='Select1'
                    placeholder="请选择一级分类"

                    onChange={firstChange}
                    options={brandArr}
                  /> ~ &nbsp;&nbsp; <Select
                    className='Select1'
                    placeholder="请选择二级分类"

                    onChange={secondChange}
                    options={brandArr2}
                  /></div>

              </div>
              <div style={{ textAlign: "center" }}>
                <button className='reset' onClick={reset} >重置</button>
                <button className='filter' onClick={searchBtn}>筛选</button>
              </div>
            </div>
          </div>
          {/* 表格 */}
          <div className='table-box'>
            <div className='table-title'>
              <div className='table-title-left'><p>数据列表</p></div>
              <div className='table-title-right'>
                <div >
                  <span style={{ marginRight: "15px" }}>排序方式</span>
                  <Select
                    dropdownStyle={{ width: '120px' }}
                    className='Select1'
                    defaultValue="排序方式"
                    onChange={handleChange3}
                    options={sort}
                  /></div>
                <div >
                  <span style={{ marginRight: "15px" }}>批量操作</span>
                  <Select
                    dropdownStyle={{ width: '120px' }}
                    className='Select1'
                    defaultValue="批量操作"
                    onChange={handleChange2}
                    options={batch}
                  /></div>

              </div>
            </div>

            <ConfigProvider locale={zh_CN}>
              <Table

                style={{ paddingLeft: '15px', fontSize: "12px" }}
                scroll={{ y: 444 }}
                rowSelection={{
                  type: selectionType,
                  ...rowSelection,
                }}
                columns={columns}
                dataSource={data}
                /* 分页 */
                pagination={{
                  position: ['bottomCenter'],
                  defaultPageSize: 3,
                  pageSize: 3,
                  pageSizeOptions: [3, 5, 8, 12],
                  showQuickJumper: true,
                  showSizeChanger: true,

                }}
              />
            </ConfigProvider>

            <Modal footer={null} title="编辑商品" cancelText='取消' okText='确认' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
              <Modify modInfo={modInfo} setIsModalOpen={setIsModalOpen} getAllShop={getAllShop}></Modify>
            </Modal>

            <Modal title="查看商品" cancelText='取消' okText='确认' open={isModalOpen2} onOk={handleOk2} onCancel={handleCancel}>
              <Check cheInfo={cheInfo}></Check>
            </Modal>
            <Modal title="生成链接" cancelText='取消' okText='确认' open={isModalOpen3} onOk={handleOk3} onCancel={handleCancel}>
              <p>商品链接为：http://www.toread.clothes.sadfadsfajpei</p>

            </Modal>
            <Modal title="删除商品" cancelText='取消' okText='确认' open={isModalOpen4} onOk={handleOk4} onCancel={handleCancel}>
              <p>是否删除该商品信息？</p>

            </Modal>

          </div>

        </div>
      </div>
    </>
  )
}

